
bt.module({builder: function(bt) {
    var j$ = jQuery;
    var map;
    var gps_points;
    var gps_bounds;
    var poly;

    var as_timezone = 0;
    var next_url = j$("#done").find("a").attr("href");

    var _updateUploadProcess = function(obj, value) {
        var _v = obj.find(".upload-progress-bar").progressbar("value");
        obj.find(".upload-progress-bar").progressbar("value", Math.max(_v, value));
        obj.find(".percentage").text(value + "%");
    };

    var _startFakeUploadProcess = function(obj, interval) {
        var current = parseInt(obj.find(".upload-progress-bar").progressbar("value"));
        var offset = parseInt(Math.random() * 15 + 5);
        if(current < 90) {
            _updateUploadProcess(obj, Math.min(90, current + offset));

            var timer = setTimeout(function() {
                _startFakeUploadProcess(obj, interval);
            }, interval);
        }
    };

    var _refreshDoneButton = function() {
        _addTimezoneUrl();
        var photo_upload = false;
        var photos = j$("#filelist .photo-tile[data-finished]");
        for (var i = 0; i < photos.length; i++) {
            if (j$(photos[i]).attr("data-finished") == "0") {
                photo_upload = true;
                break;
            }
        }

        if(gps_points || (!photo_upload && j$("#filelist .photo-tile[data-wp-id]").length > 0)) {
            j$("#done").removeClass("disabled");
        } else {
            j$("#done").addClass("disabled");
        }
    };

    var _disableDoneButton = function() {
        j$("#done").addClass("disabled");
    };

    var _addTimezoneUrl = function () {
        var _select = j$("#timezone");
        var _argu = "&tz=" + _select.val();
        j$("#done").attr("url", next_url + _argu);
    };

    var _dealWithFailedGPSUpload = function() {
        j$("#map").hide();
        j$(".upload-gps-file").show();
        j$(".upload-gps-title").hide();
        j$(".upload-gps-ajax-img").hide();
        _refreshDoneButton();
    };

    j$(document).ready(function() {
        var isIpad = navigator.userAgent.indexOf("iPad") != -1 ;
        var uploaderUrl = j$("#uploadify_script").attr("data-url");
        var uploader;
        if ( isIpad ) { // iPad
            uploader = new plupload.Uploader({
                runtimes: 'html5',
                browse_button: 'pickfiles',
                container: 'uploader',
                filters: [{title: "Image files", extensions: "tif,jpg,jpeg,png,gif"}],
                url: uploaderUrl,
                resize : {width : 1600, height : 1600, quality : 100},
                multipart: "form-data"
            });
        }else{ // not iPad
            uploader = new plupload.Uploader({
                runtimes: 'flash',
                max_retries: 0,
                //max_file_size: '10kb',
                flash_swf_url: '/static/new/plugins/Moxie.swf',
                browse_button: 'pickfiles',
                container: 'uploader',
                filters: [{title: "Image files", extensions: "tif,jpg,jpeg,png,gif"}],
                url: uploaderUrl,
                resize : {width : 1600, height : 1600, quality : 100},
                multipart: "form-data"
            });
        }

        uploader.init();

        uploader.bind('FilesAdded', function(up, files) {
            var _postFiles = function() {
                // loop through the files array
                for (var i in files) {
                    var tile = j$(".photo-tile-tpl").clone().removeClass(
                            "photo-tile-tpl").attr("data-finished", "0");
                    tile.attr("data-file-id", 'f-' + files[i].id);
                    tile.insertBefore(".upload-tile");
                    tile.show();
                    tile.find(".upload-progress-bar").progressbar();
                }

                uploader.start();
            };

            _postFiles();
        });

        uploader.bind('BeforeUpload', function(up, file) {

            _disableDoneButton();
            var tile = j$(".photo-tile[data-file-id=f-" + file.id + "]");
            _startFakeUploadProcess(tile, parseInt(file.size / 5000));

            // 添加一个监控图片上传是否超时的检查
            var lastUploadedFile = up.lastUploadedFile || undefined;

            setTimeout(function(){
                if(lastUploadedFile == up.lastUploadedFile){
                    for(var i = 0; i < up.files.length; i++){
                        if(file == up.files[i]){
                            up.stop();
                            up.splice(i, 1);
                            up.start();
                            break;
                        }
                    }
                }
            }, 300000)

        });

        uploader.bind('UploadProgress', function(up, file) {
            var tile = j$(".photo-tile[data-file-id=f-" + file.id + "]");
            _updateUploadProcess(tile, file.percent);
        });

        uploader.bind('FileUploaded', function(up, file, resp) {
            // 记录最上传的文件名称
            up.lastUploadedFile = file;

            var json = j$.parseJSON(resp.response);
            var tile = j$(".photo-tile[data-file-id=f-" + file.id + "]");
            var popup = j$("#preview-popup");
            tile.find("div.photo").mouseenter(function() {
                var _tile = j$(this).parents(".photo-tile");
                popup.find("img.preview-photo").attr("src", json.photo_url);
                popup.find(".remove").attr("data-remove-url", json.delete_url);
                popup.find(".remove").unbind("click").click(function() {
                    _disableDoneButton();
                    var _this = j$(this);
                    popup.stop(true, true).fadeOut();
                    _tile.css('opacity', 0.3);
                    _tile.find(".ajax-indicator").show();
                    j$.ajax({
                        url: _this.attr("data-remove-url"),
                        type: 'DELETE',
                        success: function() {
                            popup.stop(true, true).fadeOut();
                            _tile.fadeOut("slow", function() {
                                _tile.remove();
                                uploader.refresh();
                                _refreshDoneButton();
                            });
                        },
                        error: function() {
                            _tile.find(".ajax-indicator").hide();
                            _tile.css('opacity', 1);
                        }
                    });
                });
                popup.stop(true, true).delay(300).fadeIn();
                var left = _tile.offset().left - (popup.outerWidth() - _tile.outerWidth()) / 2;
                popup.css("left", left);
                popup.css("top", _tile.offset().top);
            });
            tile.find("div.photo").mouseleave(function() {
                var popup = j$("#preview-popup");
                if(popup.css("display") == "none") {
                    popup.stop(true, true);
                }
            });
            popup.mouseleave(function() {
                var popup = j$("#preview-popup");
                popup.stop(true, true).fadeOut();
            });

            tile.attr("data-wp-id", json.encrypted_id);
            tile.attr("data-finished", "1");
            tile.find(".photo").css("background", "url('" + json.thumbnail_url + "') center center");
            tile.find(".text, .upload-progress-bar").hide();
            tile.find(".ajax-indicator").hide();
            tile.find(".remove").attr("data-remove-url", json.delete_url);
            tile.find(".remove").click(function() {
                _disableDoneButton();
                tile.css('opacity', 0.3);
                tile.find(".ajax-indicator").show();
                j$.ajax({
                    url: json.delete_url,
                    type: 'DELETE',
                    success: function() {
                        tile.fadeOut("slow", function() {
                            tile.remove();
                            uploader.refresh();
                            _refreshDoneButton();
                        });
                    },
                    error: function() {
                        tile.find(".ajax-indicator").hide();
                    }
                });
            });
            tile.find(".remove").show();
            tile.find(".privacy-unfixed").click(function() {
                j$(this).toggleClass("public private");
            });
            tile.find(".privacy-bar").show();

            _refreshDoneButton();
        });


        uploader.bind("FilesRemoved", function(up, args){
            var tile = j$(".photo-tile[data-file-id=f-" + args[0].id + "]");
            tile.find(".text, .upload-progress-bar").hide();
            tile.find(".ajax-indicator").hide();
            tile.find(".upload-error").show();
            tile.find(".remove-retry").click(function() {
                tile.fadeOut("slow", function() {
                    tile.remove();
                    _refreshDoneButton();
                });
            });
        })


        uploader.bind('Error', function(up, args) {
            var msg = "文件" + args.file.name + "上传失败，请重新上传。";
            msg += "(" + args.code + ': ' + args.message + ")";
            alert(msg);
            var tile = j$(".photo-tile[data-file-id=f-" + args.file.id + "]");
            tile.find(".text, .upload-progress-bar").hide();
            tile.find(".ajax-indicator").hide();
            tile.find(".upload-error").show();
            tile.find(".remove-retry").click(function() {
                tile.fadeOut("slow", function() {
                    tile.remove();
                    uploader.refresh();
                    _refreshDoneButton();
                });
            });
        });

        j$('#uploadfiles').click(function() {
            uploader.start();
        });

        bt.gmap.initMapScript(function() {
            var options = {
                zoom: 14,
                mapTypeId: google.maps.MapTypeId.ROADMAP
            };
            map = new google.maps.Map(document.getElementById("map"), options);
        });

        j$("#gpsfile").ajaxForm({
            beforeSubmit: function() {
                j$(".upload-gps-ajax-img").show();
                j$("#map").show();
                bt.gmap.refreshMap(map);
            },
            success: function(resp, statusText, xhr, $form) {
                try {
                    var result = bt.misc.parseGPS(resp);
                } catch (err) {
                    result = '';
                }
                if(!result) {
                    alert("GPS文件格式错误。");
                    _dealWithFailedGPSUpload();
                    return;
                }
                gps_points = result[0];
                gps_bounds = result[1];

                poly = new google.maps.Polyline({
                    // use your own style here
                    path: gps_points,
                    clickable: false,
                    strokeColor: "#4D90FE",
                    strokeWeight: 4,
                    strokeOpacity: .7
                });

                poly.setMap(map);
                // fit bounds to track
                map.fitBounds(gps_bounds);

                j$(".upload-gps-file").hide();
                j$(".upload-gps-title").show();
                j$(".upload-gps-ajax-img").hide();
                _refreshDoneButton();
            },
            error: function() {
                alert("请求出错，请重试");
                _dealWithFailedGPSUpload();
            }
        });

        j$("#gpsfile .gpsfile-input").change(function() {
            try {
                j$("#gpsfile").submit();
            } catch (err) {
                alert(err);
                _dealWithFailedGPSUpload();
            }
        });

        j$(".upload-gps-title .remove").click(function() {
            if(poly) {
                poly.setMap(null);
                poly = null;
            }
            gps_points = null;
            gps_bounds = null;
            j$("#map").hide();
            j$(".upload-gps-file").show();
            j$(".upload-gps-title").hide();
            _refreshDoneButton();
        });

        j$("#done").click(function(e) {
            if(j$(this).hasClass("disabled")) {
                return false;
            }
            j$(this).addClass("disabled").find('p').show();
            var data = bt.misc.initPostData();
            var ids = [];
            //Collect non-public waypoint IDs
            j$(".privacy-bar.private").each(function() {
                var _id = j$(this).parents(".photo-tile").attr("data-wp-id");
                if(_id) {
                    ids.push(_id);
                }
            });
            data["pri_ids"] = ids;

            ids = [];
            //Collect public waypoint IDs
            j$(".privacy-bar.public").each(function() {
                var _id = j$(this).parents(".photo-tile").attr("data-wp-id");
                if(_id) {
                    ids.push(_id);
                }
            });
            data["pub_ids"] = ids;

            //Collect GPS track points
            if(gps_points) {
                var tracks = [];
                j$.each(gps_points, function(index, value) {
                    var track = [
                        value.lat(),
                        value.lng(),
                        value.time
                    ];
                    tracks.push(track);
                });
                data["track_count"] = tracks.length;
                data["tracks"] = tracks;
            }

            data["timezone"] = j$("#timezone").val();

            j$.ajax({
                url: j$(this).find("a").attr("href"),
                type: "POST",
                data: data,
                success: function(resp) {
                    if(!resp.error) {
                        j$(window.location).attr("href", resp.new_edit_link);
                    } else {
                        j$(this).removeClass("disabled").find('p').hide();
                    }
                }
            });
            return false;
        });
    });
}});
